import requests
import time
import sys
sys.path.append("../")
from model.StockBaseInfo import *
from frameworks.utils.PrettyTableUtil import *
from frameworks.cores.LoadClass import *
from services.CodesService import *
from services.DayKlineService import *
from frameworks.utils.RedisUtil import *
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error
import joblib
import json
import time

loader = LoadClass()
redis = RedisUtil()

"""
#f2:最新价 f3:涨幅 f4:涨跌额 f5:成交量 f6成交额 f7:振幅
#f8:换手率 f9:市盈率 f10:量比 f11: f12:代码 f14:股票名称 f15:最高
#f16:最低 f17:今开 f18:昨收 f20:总市值 f21:流通市值
#f22:
"""

base = StockBaseInfo()
klineService = DayKlineService()
def getMiniteData(code):
    print(code)
    data = klineService.getThirtyData(code)
    score = 0
    moneyscore = 0
    money_zf = 0
    n = 1
    zf = 0
    for row in data:
        #计算涨幅分数
        close = float(row["close"])
        if row["pre_close"] == None:
            score += 0
            pre = close
            zf = 0
        else:
            pre = float(row["pre_close"])
            zf = round(((close-pre)*100)/pre,2)
            score += zf*n

        money = float(row["money"])
        flow_money = close * float(row["flow_volume"])
        if close > pre:
            money_zf = round((money * 100) / flow_money, 2)
        else:
            money_zf = -1 * round((money * 100) / flow_money, 2)
        moneyscore += money_zf*n
        n += 1
    return [round(score,2),round(zf,2),round(moneyscore,2),round(money_zf,2)]

codes = []
codeService = CodeService()
#prettyTable = PrettyTableUtil(["代码", "名称", "score", "涨幅","流通市值","分时图","日线图"])
newParam = {}
obj = klineService.getTenHasZhangting()
m = 0
ck = "day_score_cache"
allrs = []
for line in obj:
    #if m > 100:
    #    break
    score,zf,money_score,money_zf = getMiniteData(line["code"])
    """
    prettyTable.addRow([line["code"], line["codename"], score, zf,round(float(line["flow_money"])/100000000,2),
                        "<img width=545 height=300 src='http://image2.sinajs.cn/newchart/min/n/" + line["code"].lower() + ".gif?'>",
                        "<img width=545 height=300 src='http://image2.sinajs.cn/newchart/daily/n/" + line["code"].lower() + ".gif?'>",
                        ])                    
    """
    """
    flow_money = round(float(line["flow_money"]) / 100000000, 2)
    df = pd.DataFrame([flow_money, score, zf],columns=["flow_money","score","zf"])
    x_test = df[['flow_money', "score", "zf"]]

    # 3）
    # 假设 X_train 是你的训练数据
    # 数据标准化
    scaler = StandardScaler()
    x_test = scaler.fit_transform(x_test)

    # 数据归一化到[0,1]范围
    min_max_scaler = MinMaxScaler()
    x_test = min_max_scaler.fit_transform(x_test)

    # 加载模型
    estimator = joblib.load("my_ridge_line.pkl")

    # 6）模型评估
    y_predict = estimator.predict(x_test)
    """
    allrs.append({
        "code": line["code"],
        "codename": line["codename"],
        "score": score,
        "zf": zf,
        "money": str(round(line["flow_money"] / 100000000)) + " 亿元",
        "divtime": "<img src='http://image2.sinajs.cn/newchart/min/n/" + line["code"].lower() + ".gif?'>",
        "daykline": "<img src='http://image2.sinajs.cn/newchart/daily/n/" + line["code"].lower() + ".gif?'>",
        "money_score": money_score,
        "money_zf": money_zf
        #"predict": y_predict[0]
    })

    """
        if score > 50:
        print("============通过===================")
        print(line["code"],line["codename"],score,zf)
        prettyTable.addRow([line["code"],line["codename"],score,zf])
    else:
        print("============未通过===================")
        print(line["code"], line["codename"], score, zf)
    """
    #break
    m += 1
#print(prettyTable.renderTable("score"))
redis.vset(ck, json.dumps(allrs))
